import { createRouter, createWebHashHistory,createWebHistory } from "vue-router";
import routes from "@/router/routes";
import useUserStore from "@/store/modules/user.js";

import userRouteStore from "@/store/modules/route.js";
import {ElLoading} from "element-plus";
import userMenuStore from "@/store/modules/menu.js";

const router=createRouter({
    history:createWebHistory(),
    routes
});



router.beforeEach(async (to, from,next) => {

    const routeStore=userRouteStore()
    let hasNewRoute=false
    if(!routeStore.routes||routeStore.routes.length===0){
        const loadingRef = ElLoading.service({
            lock: true,
            text: "正在准备路由，请稍等...",
            background: 'rgba(0, 0, 0, 0.7)',
        })


        hasNewRoute=await routeStore.fetchRoutes(router)

        loadingRef.close()
    }

    if(to.name==='logout'){
        hasNewRoute?next(to.fullPath):next()
        return;
    }

    const userStore=useUserStore()
    // ...
    // 返回 false 以取消导航

    if (to.path !== '/login' && !userStore.userInfo){
        console.log(to)
        next({ name: 'login' ,query:{redirect:to.fullPath}})
        return
    }

    const menuStore=userMenuStore()

    menuStore.setDefaultActive(to)

    hasNewRoute?next(to.fullPath):next()
})
export default router